import { Component, OnInit, ViewChild } from "@angular/core";
import "datatables";
import { ModalDirective } from "ng2-bootstrap/ng2-bootstrap";
import { ApprInfo } from "./appr-info.class";
import { CertRenewApprService } from "./certificate-renew.service";
import { DataTablesComponent, DataTablesComponentConfig } from 'app/theme/components/dataTables';
import { FormBuilder } from "@angular/forms";
import { SearchForm } from "./search-form.class";
import { CerRenewAppr } from "./cert-renew-appr.class";

@Component({
  selector: 'certificate-renew-approval',
  templateUrl: 'certificate-renew.component.html',
  styleUrls: ['certificate-renew.component.scss'],
  providers: [CertRenewApprService]
})
export class CertRenewApprComponent implements OnInit {
  @ViewChild('apprPassModal') apprPassModal: ModalDirective;
  @ViewChild('apprActivateModal') apprActivateModal: ModalDirective;
  @ViewChild('apprRejectModal') apprRejectModal: ModalDirective;
  @ViewChild('apprReviewModal') apprReviewModal: ModalDirective;
  @ViewChild('apprDeleteModal') apprDeleteModal: ModalDirective;
  @ViewChild('apprTimeModal') apprTimeModal: ModalDirective;
  @ViewChild(DataTablesComponent) dataTable: DataTablesComponent;

  private apprInfo: ApprInfo = new ApprInfo();
  private _selectdAppr: CerRenewAppr = new CerRenewAppr();
  private searchForm: SearchForm = new SearchForm();

  private apprUrl = '/water/certificate/checkCertifExtension';
  private apprInfoUrl = '/water/certificate/showCertifExtension';
  private apprActivate = '/water/certificate/activateCertifi';
  private apprTableUrl = '/water/certificate/applyCertifExten';
  private apprDownloadUrl = '/water/usersub/printSummaryTableByIds';
  private apprDeleteUrl = '/water/certificate/delete';
  private downloadTimeUrl = '/water/usersub/printSummaryTableByStage';

  private downloadUrl: string = '';
  private downloadUrlByStage = '';

  private disableReviewBtn = true;
  private disablePassBtn = true;
  private disableRejectBtn = true;
  private disableActBtn = true;
  private disableDownloadBtn = true;
  private disableDeleteBtn = true;
  private disableDownloadTimeBtn: boolean = false;

  private selectedRowData: any[];
  private _errorMsg: string;
  private errorShow = false;

  private dataTablesConfig: DataTablesComponentConfig = new DataTablesComponentConfig();

  public loading = false;

  constructor(private _fb: FormBuilder, private _service: CertRenewApprService) {
  }

  search() {
    this.dataTable.draw();
  }

  ngOnInit() {
    this.dataTablesConfig.ajaxUrl = this.apprTableUrl;
    this.dataTablesConfig.columnsDef = [
      {'name': '证书类型', 'id': 'type'},
      {'name': '证书编号', 'id': 'serialno'},
      {'name': '姓名', 'id': 'name'},
      {'name': '公司名', 'id': 'companyname'},
      {'name': '签发日期', 'id': 'issuedate'},
      {'name': '有效期', 'id': 'availabletime'},
      {'name': '提交时间', 'id': 'submittime', 'orderable': true},
      {'name': '审批时间', 'id': 'verifytime', 'orderable': true},
      {'name': '状态', 'id': 'verified'}
    ];
  }

  tableRowSelect(rowData: any[]) {
    this.disableAllButtons();
    this.selectedRowData = rowData;
    if (rowData.length > 0) {
      let length = rowData.length;
      if (length === 1) {
        this.disableReviewBtn = false;
        if (rowData[0].verified === '注销') {
          this.disableActBtn = false;
        }
        if(rowData[0].available === '无效'){
          this.disableActBtn = false;
        }
      }
      this.disablePassBtn = this.disableRejectBtn = rowData[0].verified !== '待审核';
      this.disableDownloadBtn = rowData.length == 0 || rowData[0].verified !== '通过';
      this.disableDeleteBtn = rowData.length == 0 || (rowData[0].verified !== '通过' && rowData[0].verified !== '未通过');
      if (!this.disableDownloadBtn) {
        this.downloadUrl = this.apprDownloadUrl +'?pkid=' + rowData[0].pkid;
        for (let i = 1; i < rowData.length; i++) {
          let data = rowData[i];
          this.downloadUrl = this.downloadUrl + ',' + data.pkid;
        }
        this.downloadUrl += '&type=证书延期';
      }
    }
  }

  handleError(e:any){
    if(e.type == 'error'){
      this.errorShow = true;
    }
  }

  review() {
    let pkid = this.selectedRowData[0].pkid;
    this.loadInfo(pkid);
  }

  private loadInfo(pkid: string) {
    this._selectdAppr = new CerRenewAppr();
    this._service.reviewAppr(this.apprInfoUrl, pkid)
      .then(res => {
        if (res.status === 'success') {
          this._selectdAppr = res.data;
          this.apprReviewModal.show();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }


  activate(year: number, comment: string) {
    this.loading = true;

    let info: any = {};
    let ids = [];
    for (let row of this.selectedRowData) {
      ids.push(row.ids);
    }
    info.ids = ids;
    info.verifydescription = comment;
    info.year = year;

    this._service.activateCert(this.apprActivate, info).then(result => {
      if (result.status === 'success') {
        this.dataTable.draw(false);
        this.apprActivateModal.hide();
      } else {
        this._errorMsg = result.data;
      }
      this.loading = false;
    }, error => {
      this._errorMsg = error;
    });
  }

  showPassModal() {
    this.apprPassModal.show();
  }

  showActivateModal() {
    this.apprActivateModal.show();
  }

  showRejectModal() {
    this.apprRejectModal.show();
  }

  showDeleteModal(){
    this.apprDeleteModal.show();
  }

  showTimeModal() {
    this.apprTimeModal.show();
  }

  onHideModal(): void {
    jQuery('.modal-backdrop').remove();
  }

  updateDateRange(event) {
    this.searchForm.startdate = this.date2String(event.beginDate);
    this.searchForm.enddate = this.date2String(event.endDate);
  }

  getStage(event) {
    const startdate = this.date2String(event.beginDate);
    const enddate = this.date2String(event.endDate);
    this.downloadUrlByStage = this.downloadTimeUrl + '?startdate=' + startdate + '&enddate='+ enddate +'&type=证书核发';
  }


  private date2String(date: any): string {
    if (Object.keys(date).length === 0 || date === null || date === undefined || (date.year == 0&&date.month==0&&date.day==0)) {
      return null;
    }

    let str = date.year + '-';
    if (date.month < 10) {
      str += '0';
    }
    str += date.month + '-';

    if (date.day < 10) {
      str += '0';
    }
    str += date.day;
    return str;
  }

  public pass(comment: string): void {
    this._saveAppr(0,comment, 'pass', this.apprPassModal);
  }

  public reject(comment: string): void {
    this._saveAppr(0, comment, 'reject', this.apprRejectModal);
  }

  public apprRejectClose() {
    this._errorMsg = null;
    this.apprRejectModal.hide();
  }

  public apprPassClose() {
    this._errorMsg = null;
    this.apprPassModal.hide();
  }

  public apprActivateClose() {
    this._errorMsg = null;
    this.apprActivateModal.hide();
  }

  public apprDeleteClose(){
    this._errorMsg = null;
    this.apprDeleteModal.hide();
  }

  public apprTimeClose() {
    this._errorMsg = null;
    this.apprTimeModal.hide();
  }


  private _saveAppr(year,comment, apprStatus, modal: ModalDirective) {
    this.loading = true;
    let ids = [];
    for (let row of this.selectedRowData) {
      ids.push(row.ids);
    }
    this.apprInfo.ids = ids;

    this.apprInfo.verifydescription = comment;
    this.apprInfo.flag = apprStatus;
    this.apprInfo.year = year;
    this._service.submitAppr(this.apprUrl, this.apprInfo).then(result => {
      if (result.status === 'success') {
        modal.hide();
        this.apprReviewModal.hide();
        this.dataTable.draw(false);
      } else {
        this._errorMsg = result.data;
      }

      this.loading = false;
    }, error => {
      this._errorMsg = error;
    });
  }

  public delete():void{
    let pkids = [];
    for(let row of this.selectedRowData){
      pkids.push(row.pkid);
    }
    this._service.deleteAppr(this.apprDeleteUrl, pkids)
      .then(res => {
        if (res.status === 'success') {
          this.apprDeleteModal.hide();
          this.dataTable.draw(false);
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }


  private disableAllButtons() {
    this.disableReviewBtn = this.disableActBtn = this.disablePassBtn = this.disableRejectBtn = this.disableDownloadBtn = this.disableDeleteBtn = true;
  }
}
